var pGrid,pGrid1, pGridData, opt, picking_id, udata,picking_data;
var testSelectTag;
var EmployeeData;
$(function() {
    //ldz 设置表单高度
    $("#form_core").height($(".form_tab").height()-$("#form_option").outerHeight());
    var param = new Object();
    param.p=false;
    var url = "/employee/query";
    var data = JSON.stringify(param);
    if (url){
        ajaxSubmit(url, data, function(data) {
            if (data!=null) {
            	EmployeeData=data;
            }
        });
    }
	// 明细列表设置
   	pGrid = $("#p-div").ligerGrid({
        columns:[
            {display:'授权类别',name:'licenseType',width:'10%',
            	editor: { type: 'text',name:'licenseType' },
            },
            {display:'授权名称',name:'licenseName',width:'10%',
            	editor: { type: 'text',name:'licenseName' },
            },
            {display: '操作', name: 'option', width: '4%',
            	editor: { type: 'button'},
                render: function(rowdata, rowindex, value) {
                    return "<a href='javascript:void(0);' onclick=deleteRow('" + rowindex + "')><span class='glyphicon glyphicon-trash'></span></a> ";
                }
            }
        ], 
        pageSize:20, 
        width:'98%',//ldz
        height:'99%', 
        rownumbers:true,
        fixedCellHeight:false, 
        enabledEdit:true, 
        onSelectRow:function(rowdata, rowindex){$("#txtrowindex").val(rowindex);},
        param_partner:'partner_list',
        alternatingRow: true,
        clickToEdit: true,
        isScroll: false,
        usePager:false,
        editorTopDiff:4,
        editorLeftDiff:2
	});
   	bindSelect('cardDept',get_org("1"),null,false);
   	
});


// 界面校验
function validate() {
	if($("#userid").val()==""||$("#userid").val()==null){
		$.ligerDialog.error('员工编号不能为空。', '错误');
		return false;
	}
	if($("#name").val()==""||$("#name").val()==null){
		$.ligerDialog.error('员工姓名不能为空。', '错误');
		return false;
	}
	if($("#cardid").val()==""||$("#cardid").val()==null){
		$.ligerDialog.error('员工卡ID不能为空。', '错误');
		return false;
	}
	if($("#cardDept").val()==""||$("#cardDept").val()==null){
		$.ligerDialog.error('发卡部门不能为空。', '错误');
		return false;
	}
	if($("#create_uid").val()==""||$("#create_uid").val()==null){
		$.ligerDialog.error('制卡人不能为空。', '错误');
		return false;
	}
	if($("#create_date").val()==""||$("#create_date").val()==null){
		$.ligerDialog.error('制卡时间不能为空。', '错误');
		return false;
	}
	if($("#create_address").val()==""||$("#create_address").val()==null){
		$.ligerDialog.error('制卡地址不能为空。', '错误');
		return false;
	}
	if (pGrid.rows.length === 0) {
		$.ligerDialog.error('请添加门禁信息。', '错误');
		return false;
	}
	if(OpenDevice()){
		if(RfWrite()){
			if(CloseDevice()){
				
			}else{
				return false;
			}
		}else{
			return false;
		}
	}else{
		return false;
	}
	
	
	return true;
}

// 保存处理方法 ，新增及修改 。
function toSave() {
	//单据校验
	if (!validate()){
		return;
	}
	var url;
	// 设置 主表数据
	var param = $('#basic_form').serializeObject();
	param.cardType="IC";
	// 更新 主表数据	 	
	url = "/employeeCard/saveEmployeeCard";
	// 设置 明细数据
	var items = pGrid.rows;
	param.items = items;
	// 提交后台保存数据转换为JSON 格式
	var data = JSON.stringify(param);
	//保存提交后台
	if (url)
		ajaxSubmit(url, data, function(data) {
			if (data['added']) {
				var picking = data['added'];
				picking_id = picking['id'];
			}
			if (parseInt(data['status']) > 0) {
				$.ligerDialog.success('信息保存成功,卡片初始化成功。', '操作完成', reloadPage);
				
			} else {
				$.ligerDialog.error('保存失败');
			}
			
		});

}
// 删除明细
function deleteRow(id) {
//	var row = pGrid.getSelectedRow();//ldz
	var row = pGrid.getRow(id);
	if (!row) {
		$.ligerDialog.error('请先选择入库商品记录。', '错误');
		return;
	}
	$.ligerDialog.confirm('您确定要删除该项数据吗？', function(r) {
		if (!r)
			return;
		if (row.__status === 'add') {
			pGrid.deleteRow(row);
			if (pGrid.row && pGrid.row.length === 0)
				pGrid.data = {};
			return;
		}
		var param = new Object();
		param.id = row.id
		var data = JSON.stringify(reqObj('d', 'stock.delete.stock_move', JSON
				.stringify(param)));
		ajaxSubmit("/cm/rbac/cm.do?m=d", data, function(data) {
			if (data) {
				if (parseInt(data['status']) > 0) {
					$.ligerDialog.success('删除成功');
					pGrid.deleteRow(row);
				} else {
					$.ligerDialog.error('删除失败');
				}
			}
		});
	});
}
// 界面重新载入
function reloadPage() {
	window.location = './employeeCardManage.html?o=m&picking_id='
			.concat(picking_id);
}
//界面的返回处理，实际是关闭标签处理。
function toBack() {
	//关闭修改界面
	parent.tabManager.removeTabItem("10030201");
}
//清空表单
function resetArea() {
	toReset('#a_center input:not(.readonly),select,textarea');
}
//新增一行ldz
function addNewRow()
{
	var newRow = pGrid.addRow({});
}
//新增一行ldz
function addNewRow1()
{
	pGrid1.addRow({});
}

var manager, g;
function f_initGrid(){ 
   g =  manager = $("#pop_div #form_table").ligerGrid({
        columns: [
            { display: '员工编号', name: 'userid',width: '10%'},
            { display: '身份证号', name: 'ssn',width: '30%'},
            { display: '性别', name: 'sex',width: '10%'},
            { display: '姓名', name: 'name',width: '10%'},
            { display: '手机', name: 'mobile_phone',width: '20%'},
            { display: '住址', name: 'address',width: '20%'},
            { display: '固话', name: 'fix_phone',width: '20%'},
            { display: '所属公司', name: 'company_id',width: '20%'},
            { display: '所属部门', name: 'dept_id',width: '20%'},
        ],
        onSelectRow: function (rowdata, rowindex)
        {
            $("#txtrowindex").val(rowindex);
        },
        enabledEdit: true,clickToEdit: true, isScroll: false,  
        data:EmployeeData,
        checkbox: true, //是否显示复选框
        pageSize: 20, //每页行数
        alternatingRow: true, //是否附加奇偶行效果行
        usePager:true,
        editorTopDiff:2,
        editorLeftDiff:2
    });   
}
//弹窗
$(function(){
	$('#pop_add_button').bind('click',function(){
		var data = manager.getSelectedRow();
		var pop_add_form = $('#form_content');
	    pop_add_form.find('input:not(:button)').each(function(i){
	    	$(this).val(data[""+$(this).attr('name')+""]);
	    });
	});
});
function help_pop(){
	$('#addMx_Modal').on('shown.bs.modal', function () {
	  f_initGrid();
	});
	$('#addMx_Modal').modal('show');
}
function display_help(){
	$("#help").css("display","inline");
}
function help_hidden(){
	
}
//--------------------------员工卡ocx方法开始-----------------------------
function OpenDevice() //打开设备
{
	var st = document.all("CActiveXCtrl").OpenDevice();
	if ((st == 0 || st < 0) && document.all("CActiveXCtrl").lErrorCode != 0) {
		document.all("DeviceHandle").value = "-1";
		$("#info").html("打开设备失败");
		return false;
	} else {
		document.all("DeviceHandle").value = st;
		return RfReset();
	}
}
function RfReset() {
	var resettime="10";
	var ret = document.all("CActiveXCtrl").RfReset(document.all("DeviceHandle").value, resettime);
	if (document.all("CActiveXCtrl").lErrorCode == 0) {
		return RfCard();
	} else {
		$("#info").html("请连接读卡器" );
		return false;
	}
}
function RfCard() {
	var ret = document.all("CActiveXCtrl").RfCard(document.all("DeviceHandle").value, 0);
	if (document.all("CActiveXCtrl").lErrorCode == 0) {
		document.all("cardid").value = ret;
		return RfAuthenticationKey();
	} else {
		document.all("cardid").value = "";
		$("#info").html("寻卡失败");
		return false;
	}
}
var defpsw="ffffffffffff";
function RfAuthenticationKey() {
	var keytype ="0"; //获取下拉框当前选值
	var ret = document.all("CActiveXCtrl").RfAuthenticationKey(document.all("DeviceHandle").value, keytype, document.all("BlockM1").value, defpsw);
	if (document.all("CActiveXCtrl").lErrorCode == 0) {
		$("#info").html("校验密码成功");
		return true;
	} else {
		$("#info").html("校验密码失败");
		return false;
	}
}


function RfWrite() {
	var writeDate="00000000000000000000000000"+document.all("userid").value;
	var ret = document.all("CActiveXCtrl").RfWrite(document.all("DeviceHandle").value, document.all("BlockM1").value, writeDate);
	if (ret == 0) {
		$("#info").html("写数据成功");
		RfBeep();
		return true;
	} else {
		$("#info").html("写数据失败");
		return false;
	}
}

function RfBeep() {
	var ret = document.all("CActiveXCtrl").RfBeep(document.all("DeviceHandle").value, 20);
}
function CloseDevice() //关闭设备
{
	var ret = document.all("CActiveXCtrl").CloseDevice(document.all("DeviceHandle").value);
	document.all("DeviceHandle").value = "-1";
	if (ret == 0){
		//alert("关闭设备成功");
		return true;
	}	else{
		$("#info").html("关闭设备失败");
		return false;
	}
}
